<?php
/**
 * Created by PhpStorm.
 * User: china
 * Date: 2015/11/24
 * Time: 16:22
 */

namespace Application\UserCenter\Controller;


use J\Schema\Sprite;
use J\Schema\Syntax;
use J\Exception;
use J\Intent;
use J\Message;
use J\MVC\Controller;
use J\Util\User;

/**
 *  用户登录、退出
 *    内部提供基础的权限验证操作
 *  不要将需要权限的操作放在这里实现
 *
 */
class GatewayController extends Controller
{
    const INDEX = 'index.php/admin/index/index';

    /**
     * 登陆认证API
     * @param Intent $intent
     * @throws Exception
     */
    protected function optionApiLogin(Intent $intent)
    {
        $data   = [];
        $status = false;
        $msg    = '';
        if(
            isset($_REQUEST['verify'])
            and $this->checkVerify($_REQUEST['verify'])
            and $this->loginUser()
        ){
            $status = true;
            $next = $intent->getContext()->getUrl()->pop();
            $data['redirect'] = empty($next) ? self::INDEX : $next;
        }else{
            $msg  =Message::MSG_LOGIN_FAIL;
        }

        $intent->ajax($status, $msg, $data);
    }

    /**
     * 验证码校验
     * @param $value
     * @return bool
     */
    protected function checkVerify($value)
    {
        $r = $this->module->fetch('/System/Verify/Check', ['verify' => $value]);
        return !$r->isError() and $r->getValue();
    }

    /**
     * 登录接口
     * @throws Exception
     */
    protected function optionLogin()
    {
        $this->loginUser();
    }

    /**
     * 退出接口
     */
    protected function optionExit()
    {
        $this->getApp()->User()->logout();
    }

    //////////////////////////接口//////////////////////////////////////

    /**
     * 用户登陆
     * @return bool 成功与否
     * @throws Exception
     */
    public function loginUser()
    {
        $collection = $this->module->getModels()->getCollection('user');

        $curd = $collection->getCurd()->setElements(['password', 'name', 'nickname'])
            ->setWhere(['name', new Sprite(Syntax::KEY_STATUS, 0, '>')]);
        $r = $curd->find();

            //->select();

        // var_dump(app()->Console()->getTrace());
        // var_dump($r);
        // console_debug(var_export($r, true));
        // die();

        // 密码检查
        if(!Password::isEqual($r['password'])) return false;

        // 记录登录信息
        $collection->getCurd()->setElements(['last_time'=>time(), 'last_ip'=>(int)get_client_ip(1)])
            ->setIds($r['id'])->edit();

        // 登陆用户
        $this->getApp()->User()->login($r);

        return true;

    }

    /**
     * 获取权限列表
     * @param Intent $intent
     * @throws Exception
     */
    protected function optionFetchAuthorize(Intent $intent)
    {
        /** @var User $user */
        $user = $intent->get('user');
        $auth = $this->getAuthorizeByRoles($user->roles);
        $intent->value = $auth;
    }

    /**
     * 获取当前用户角色信息
     * @param Intent $intent
     * @throws Exception
     */
    protected function optionFetchRoles(Intent $intent)
    {
        /** @var User $user */
        $user = $intent->get('user');

        $intent->value = $user->isAdministrator() ? true : $this->getRolesById($user->getId());
    }

    /**
     * 获取指定用户部门
     *
     * @param int $uid 用户ID
     *
     * @return array
     *
     * @throws Exception
     */
    protected function getDepartmentsById($uid)
    {
        return $this->getModule()->getModels()->getCollection('department')
            ->getCurd()->setWhere(['user' => $uid])->select();
    }

    /**
     * 获取指定用户的权限信息
     *
     * @param int $uid 用户ID
     *
     * @return array
     *
     * @throws Exception
     */
    protected function getAuthorizeById($uid)
    {
        return $this->getAuthorizeByRoles($this->getRolesById($uid));
    }

    /**
     * 获取指定用户角色信息
     *
     * @param int $uid 用户ID
     *
     * @return array
     *
     * @throws Exception
     */
    protected function getRolesById($uid)
    {
        $roles = $this->getCollection('role')->getCurd()
            ->setWhere(['user' => $uid, new Sprite('status', 0, '>')])
            ->setElements(['title'])
            ->select();

        return $roles;
    }

    /**
     * 根据角色信息获取权限列表
     *
     * @param $roles
     * @return array
     * @throws Exception
     */
    protected function getAuthorizeByRoles($roles)
    {
        $curd = $this->module->getModels()->getCollection('resource')->getCurd();

        $where = $curd->getWhere();

        $i = $where->andCondition([new Sprite('status', '0', '>')]);
        if ($roles !== true)
            $where->andCondition(['role' => array_column_unique($roles, Syntax::KEY_ID)], $i);


        return $curd->setElements(Syntax::KEY_ALL)
            ->setRaw(true)
            ->select();
    }
}